var network = require("../../utils/request.js"); //网络请求
const utils = require('../../utils/util');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: {
      pageSize: 10,
      pageNum: 1
    },
    total:0,
    isLoging : false,
    key: "",
    // bananerImg: ["../../resource/images/bg_gongying.png"],//已经通过网络获取此处不需要本地的
    bananerImg: [],
    icon_img: "../../resource/images/arrow_down.png",
    toSupplyImg: "../../resource/images/to_supply.gif",//发布供应图片

    inputValue: '',//点击结果项之后替换到文本框的值
    bindSource: [],//绑定到页面的数据，根据用户输入动态变化
    isShowHint:false,//是否显示联想内容

    arrayOne: [{"standard":"规格"}],
    region: ['全部', '全部', '全部'],

    indexOne: 0,
    customItem: '全部',
    items: [], //列表数据源
    noData: "../../resource/images/noData.png",//无数据图片
    goodsImg:"../../resource/images/share.jpg",//商品图
    call_img: "../../resource/images/call.png",//打电话图标
    like_img: "../../resource/images/like.png",//已点赞图标
    to_like_img: "../../resource/images/toLike.png",//点赞图标
    transmit_img: "../../resource/images/transmit.png",//转发图标
    hot_img: "../../resource/images/hot.png",//推荐图标
    userInfo:{},//存放用户信息
    
  },
  //当键盘输入时，触发input事件
  bindiName: function (e) {
    var that = this
    var prefix = e.detail.value//用户实时输入值
    if (prefix != "") {
      //通过接口查询数据
      network.post('getTradeByName/' + prefix).then(resp => {
        console.log(resp.rows)
        if (resp.rows.length > 0){
          that.setData({
            bindSource: resp.rows,
            isShowHint: true
          })
        }else{
          that.setData({
            bindSource: [],
            isShowHint: false
          })
        }
      })


    }

  },

  itemtap: function (e) {
    this.setData({
      inputValue: e.target.id,
      bindSource: [],
      isShowHint: false
    })

    //获取规格下拉数据源
    network.post('getGoodsByName/' + e.target.id).then(resp => {
      console.log(resp)
      if (resp.rows.length > 0) {
        resp.rows.unshift({
          "standard": "规格"
        })
        this.setData({
          arrayOne: resp.rows
        })
      }else{
        let arr = {"standard":"规格"}
        this.setData({
          arrayOne: arr
        })
      }
    })

  },

  //下拉事件
  bindPickerChangeOne: function (e) {
    this.setData({
      indexOne: e.detail.value
    })
    this.data.page.pageNum = 1
    this.data.items = []
    var standard = this.data.arrayOne[e.detail.value].standard
    this.queryProvision({
      "standard": standard
    })

  },
  
  //区域选择
  bindRegionChange(e) {
    this.setData({
      region: e.detail.value
    })
    this.data.page.pageNum = 1
    this.data.items = []
    this.queryProvision({
      'province': e.detail.value[0],
      'city': e.detail.value[1],
      'area': e.detail.value[2],
    })
  },

  //跳转到发布供应
  toSupply() {
    console.log(this.data.userInfo)
    if (this.data.userInfo.nickName === ""){
      wx.showToast({
        title: '请先登录!',
        icon:"none"
      })
      setTimeout(function(){
        wx.navigateTo({
          url: '../home/home',
        })
      },1000)
    } else{
      if (this.data.userInfo.mobile === ""){
        wx.showToast({
          title: '请先完善信息!',
          icon: "none"
        })
        setTimeout(function () {
          wx.navigateTo({
            url: '../userInfo/userInfo',
          })
        }, 1000)
      }else{
        //跳转到发布供应
        wx.navigateTo({
          url: '../supply/supply',
        })
      }
    }
  },

  //列表项点击事件
  clickItem(e){
      wx.navigateTo({
        url: 'supplyListDetail/supplyListDetail?id=' + e.currentTarget.dataset.id + '&&index=' + e.currentTarget.dataset.index
      })
  },

  //点赞
  clickLike(e) {
    if (this.data.userInfo.mobile == "") {
      wx.showToast({
        title: '请先完善信息',
      })
      return
    }
    
    let that = this
    let likeId = e.currentTarget.dataset.id
    network.post("likeProvision/" + likeId).then(resp => {
      if (resp.rows == 1){
        wx.showToast({
          title: '点赞成功',
        })

        //修改页面点赞图标，等接口修改字段
        that.data.items[e.currentTarget.dataset.index].likeFlag = true
        that.data.items[e.currentTarget.dataset.index].likeNum = that.data.items[e.currentTarget.dataset.index].likeNum + 1
        that.setData({
          items: that.data.items
        })
      }else{
        wx.showToast({
          title: '您已点过了',
          icon: 'none'
        })
      }
    })
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    //获取列表数据
    this.queryProvision()

    //获取轮播图
    this.getCarousel()

  },
  queryProvision(query = {}) {
    //获取供应列表
    Object.assign(this.data.page, query)
    network.post('queryProvision', this.data.page).then(resp => {
      console.log(resp.rows)
      let arrInfo = this.data.items //点赞无效，刷新可以
      arrInfo.push(...resp.rows)
      this.setData({
        items: arrInfo,
        total: resp.total,
        isLoging: false,
      })
    })
  },

  //更新列表上的点赞和呼叫数据
  updateLikePhone(that,id,index){
    network.post('getProvisionSimple/'+id).then(resp => {
      that.data.items[index].likeNum = parseInt(resp.rows.likeNum)
      if (parseInt(resp.rows.likeNum) > 0){
        that.data.items[index].likeFlag = true
      }
      
      // that.data.items[index].shareNum = parseInt(resp.rows.shareNum)
      this.setData({
        items: that.data.items
      })
    })
  },

  //获取轮播图
  getCarousel () {
    //供应专区，参数：1
    network.post('getCarousel/1').then(resp => {
      var imgArr = []
      for (var i = 0; i < resp.rows.length; i++) {
        imgArr[i] = network.imgUrl + resp.rows[i].imageId
      }
      this.setData({
        bananerImg: imgArr
      })
    })
  },

  //下拉刷新
  onPullDownRefresh() {
    this.data.page.pageNum = 1;
    this.data.items = [];
    this.queryProvision()

    //清空banner图数据
    this.data.bananerImg = []
    //重新获取轮播图
    this.getCarousel()
    wx.pageScrollTo({
      scrollTop: 0
    })
    wx.stopPullDownRefresh()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let userInfo = wx.getStorageSync("userInfo")
    this.setData({
      userInfo: userInfo
    })

    let id = app.globalData.backSupplyListId
    let index = app.globalData.backSupplyListIndex

    //如果详情页执行了点赞操作，则查询接口
    if(id != -1){
      this.updateLikePhone(this,id,index)
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    //加载更多
    var total = parseInt(this.data.total)
    var pageNum = this.data.page.pageNum
    var pageCount = Math.ceil(total / this.data.page.pageSize)
    console.log(total, pageNum, pageCount)
    if (pageNum < pageCount && !this.data.isLoging) {
      this.data.isLoging = true
      this.data.page.pageNum = ++pageNum
      this.queryProvision()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '跑合中药材供需云平台',
      imageUrl: '../../resource/images/share.jpg',
      path: 'pages/supplyList/supplyList',
      success: function (res) {
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '分享取消',
        })
      }
    }
  }
})